package com.ldcc.report_system.ui.report;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ldcc.report_system.ReportApplication;
import com.ldcc.report_system.adapter.WeekListAdapter;
import com.ldcc.report_system.api.results.PageResult;
import com.ldcc.report_system.api.results.WeekReportResult;
import com.ldcc.report_system.databinding.FragmentWeekListBinding;
import com.ldcc.report_system.util.http.ClientRequestManage;
import com.ldcc.report_system.util.http.HttpObserver;
import com.ldcc.report_system.util.http.ServerResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author wwj[yeshengkele@outlook.com]
 * @description 周报列表
 */
public class WeekListFragment extends Fragment {
    private FragmentWeekListBinding weekListBinding;
    // 数据适配器
    private WeekListAdapter weekListAdapter;
    // 数据
    protected List<WeekReportResult> reportList = new ArrayList<>();
    // 当前页,多线程环境使用原子操作类
    private AtomicLong currentPage = new AtomicLong(1);
    // 所有页
    protected AtomicLong countPage = new AtomicLong(1);
    // 是否在更新状态
    private boolean isLoading = false;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.weekListBinding = FragmentWeekListBinding.inflate(inflater, container, false);
        // 初始化
        this.init();
        return this.weekListBinding.getRoot();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void init() {
        // 初始化适配器
        this.weekListAdapter = new WeekListAdapter(this.reportList, getActivity());
        // 设置数据适配器
        this.weekListBinding.weekList.setAdapter(this.weekListAdapter);
        // 设置RecyclerView为垂直布局布局
        this.weekListBinding.weekList.setLayoutManager(new LinearLayoutManager(getContext()));
        // 设置刷新事件
        this.weekListBinding.refresh.setOnRefreshListener(() -> {
            if (!isLoading) {
                //显示刷新动画效果
                this.weekListBinding.refresh.setRefreshing(true);
                // 刷新数据需要清空数据
                this.weekListAdapter.updateWeekReport(new ArrayList<>());
                // 设置为首页
                this.currentPage.set(1);
                //重新获取数据
                setReportDataByPage(this.currentPage, true);
            }
        });
        // 设置加载更多数据事件
        this.weekListBinding.weekList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!recyclerView.canScrollVertically(1)) {
                    //滑动到底部
                    if (!isLoading) {
                        // 添加一页
                        currentPage.getAndIncrement();
                        //加载更多数据
                        setReportDataByPage(currentPage, false);
                    }
                }
            }
        });

        // 设置默认获取数据
        this.setReportDataByPage(new AtomicLong(1), false);
    }

    @Override
    public void onResume() {
        //显示时所作的事情
        super.onResume();
    }

    /**
     * @param isRefresh 是否为下拉刷新操作
     * @param page      需要第几页数据
     * @description 从第一页开始刷新数据
     */
    public void setReportDataByPage(AtomicLong page, boolean isRefresh) {
        if (page.get() <= this.countPage.get()) {
            // 设置当前页
            this.currentPage = page;
            // 开始加载
            this.isLoading = true;
            ClientRequestManage.getInstance().getWeekReportApi().get(currentPage.get())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new HttpObserver<PageResult<WeekReportResult>>(ReportApplication.getContext(), null){

                        @Override
                        public void onSuccess(ServerResponse<PageResult<WeekReportResult>> response_entity) {
                            // 设置总页数
                            countPage = new AtomicLong(response_entity.getData().getTotal());
                            // 设置底部加载效果
                            weekListAdapter.setHasMore(page.get() < countPage.get());
                            List<WeekReportResult> records = response_entity.getData().getRecords();
                            // 设置数据
                            reportList.addAll(records);
                            // 通知更新列表
                            weekListAdapter.updateWeekReport(reportList);
                            // 清除数据以及提示效果
                            if (isRefresh) {
                                // 隐藏刷新效果
                                weekListBinding.refresh.setRefreshing(false);
                            }
                            // 结束加载
                            isLoading = false;
                        }
                    });
        }
    }

}